package com.tim.app.ui.adapter.friend;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.application.library.net.StringResponseCallback;
import com.application.library.runtime.event.EventManager;
import com.application.library.widget.recycle.BaseRecyclerAdapter;
import com.application.library.widget.roundimg.RoundedImageView;
import com.google.gson.Gson;
import com.tim.app.R;
import com.tim.app.RT;
import com.tim.app.constant.AppKey;
import com.tim.app.constant.EventTag;
import com.tim.app.server.api.API_User;
import com.tim.app.server.logic.UserManager;
import com.tim.app.server.result.ResponseResult;
import com.tim.app.server.result.UserFollowResult;
import com.tim.app.server.result.UserRelationStatedResult;
import com.tim.app.ui.activity.some_homepage.SomeoneHomepageActivity;
import com.tim.app.util.BitmapLoader;
import com.tim.app.util.ToastUtil;
import com.tim.app.util.ViewGT;

import java.util.List;


/**
 * 用户
 */
public class UserAdapter extends BaseRecyclerAdapter<BaseRecyclerAdapter.BaseRecyclerViewHolder, UserFollowResult.Res.Data.FollowUser> {

    private static final String TAG = "UserAdapter";

    private Context mContext;


    private boolean isShow;
    private int type;

    public UserAdapter(Context mContext, List<UserFollowResult.Res.Data.FollowUser> mDataList, int type, boolean isShow) {
        super(mDataList);
        this.mContext = mContext;
        this.type = type;
        this.isShow = isShow;
    }

    @Override
    public BaseRecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        BaseRecyclerViewHolder holder = null;
        holder = new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.cell_user, parent, false));
        return holder;
    }

    @Override
    public void onBindViewHolder(BaseRecyclerViewHolder mHolder, final int position, final UserFollowResult.Res.Data.FollowUser data) {
        if (data == null || null == data.getUserMsg()) {
            return;
        }
        final ViewHolder holder = (ViewHolder) mHolder;
        BitmapLoader.ins().loadImage(data.getUserMsg().getImage(), holder.rivAvatar);
        if (!TextUtils.isEmpty(data.getUserMsg().getName())) {
            holder.tvUserName.setText(data.getUserMsg().getName());
        } else {
            holder.tvUserName.setText("");
        }
        if (!TextUtils.isEmpty(data.getUserMsg().getIntroduce())) {
            holder.tvDesc.setText(data.getUserMsg().getIntroduce());
        } else {
            holder.tvDesc.setText("个人签名");
        }
        holder.tvLevel.setText(mContext.getString(R.string.userLevel, String.valueOf(data.getUserMsg().getLevelId())));
        if (data.getUserMsg().getSex() == 1) {
            Drawable manDrawable = mContext.getResources().getDrawable(R.drawable.ic_male);
            manDrawable.setBounds(0, 0, manDrawable.getMinimumWidth(), manDrawable.getMinimumHeight());
            holder.tvInfo.setCompoundDrawables(manDrawable, null, null, null);
            holder.tvInfo.setCompoundDrawablePadding((int) RT.getDensity() * 1);
            holder.tvInfo.setSelected(false);
        } else if (data.getUserMsg().getSex() == 2) {
            Drawable manDrawable = mContext.getResources().getDrawable(R.drawable.ic_female);
            manDrawable.setBounds(0, 0, manDrawable.getMinimumWidth(), manDrawable.getMinimumHeight());
            holder.tvInfo.setCompoundDrawables(manDrawable, null, null, null);
            holder.tvInfo.setCompoundDrawablePadding((int) RT.getDensity() * 1);
            holder.tvInfo.setSelected(true);
        }
        holder.tvInfo.setText(String.valueOf(data.getUserMsg().getAge()));
        if (position == getDataList().size() - 1) {
            holder.vLine.setVisibility(View.GONE);
        } else {
            holder.vLine.setVisibility(View.VISIBLE);
        }

        if (data.getFriendType() == AppKey.RELATIONSHIP_TYPE_FRIEND) {
            holder.tvFollow.setSelected(true);
            holder.tvFollow.setText(R.string.followed);
        } else if (data.getFriendType() == AppKey.RELATIONSHIP_TYPE_FOLLOW) {
            holder.tvFollow.setSelected(true);
            holder.tvFollow.setText(R.string.hasFollow);
        } else {
            holder.tvFollow.setSelected(false);
            holder.tvFollow.setText(R.string.unFollow);
        }
        if (UserManager.ins().isLogin() && UserManager.ins().getUserId().equals(data.getUserMsg().getUserId())) {
            holder.tvFollow.setVisibility(View.GONE);
        } else {
            holder.tvFollow.setVisibility(View.VISIBLE);
        }

        holder.tvFollow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!UserManager.ins().isLogin()) {
                    ViewGT.gotoLoginActivity(mContext);
                    return;
                }
                holder.tvFollow.setEnabled(false);
                if (AppKey.RELATIONSHIP_TYPE_NORMAL != data.getFriendType()) {
                    API_User.ins().cancelFollowUser(TAG, UserManager.ins().getUserId(), data.getUserMsg().getUserId(), new StringResponseCallback() {
                        @Override
                        public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
                            holder.tvFollow.setEnabled(true);
                            if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                                UserRelationStatedResult result = new Gson().fromJson(resultValue, UserRelationStatedResult.class);
                                if (null != result && null != result.getRes()) {
                                    int friendType = result.getRes().getFriend().getFriendType();
                                    getDataList().get(position).setFriendType(friendType);
                                    notifyItemChanged(position);
                                    EventManager.ins().sendEvent(EventTag.ON_USER_CANCEL_FOLLOW, type, 0, getDataList().get(position));
                                }
                            } else {
                                ToastUtil.showToast(errMsg);
                            }
                            return false;
                        }
                    });
                } else {
                    API_User.ins().followUser(TAG, UserManager.ins().getUserId(), data.getUserMsg().getUserId(), new StringResponseCallback() {
                        @Override
                        public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
                            holder.tvFollow.setEnabled(true);
                            if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                                UserRelationStatedResult result = new Gson().fromJson(resultValue, UserRelationStatedResult.class);
                                if (null != result && null != result.getRes()) {
                                    int friendType = result.getRes().getFriend().getFriendType();
                                    getDataList().get(position).setFriendType(friendType);
                                    notifyItemChanged(position);
                                    EventManager.ins().sendEvent(EventTag.ON_USER_FOLLOW, type, 0, getDataList().get(position));
                                }
                            } else if (ResponseResult.ResultStatus.BE_ADD_BLACK == errCode) {
                                if (data.getUserMsg().getSex() == AppKey.SEX_MAN) {
                                    ToastUtil.showToast("由于对方的设置，你不能关注他");
                                } else {
                                    ToastUtil.showToast("由于对方的设置，你不能关注她");
                                }
                            } else {
                                ToastUtil.showToast(errMsg);
                            }
                            return false;
                        }
                    });
                }
            }
        });

        holder.tvUserName.setTag(data);
        holder.rivAvatar.setTag(data);
        holder.tvUserName.setOnClickListener(onClickListener);
        holder.rivAvatar.setOnClickListener(onClickListener);
    }

    View.OnClickListener onClickListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            UserFollowResult.Res.Data.FollowUser user = (UserFollowResult.Res.Data.FollowUser) v.getTag();
            SomeoneHomepageActivity.start(mContext, user.getUserMsg(), false);
        }
    };

    public class ViewHolder extends BaseRecyclerViewHolder {

        RoundedImageView rivAvatar;
        TextView tvUserName;
        ImageView ivVip;
        TextView tvInfo, tvLevel, tvDesc;
        View vLine;
        TextView tvFollow;

        public ViewHolder(View itemView) {
            super(itemView);
            rivAvatar = (RoundedImageView) itemView.findViewById(R.id.rivAvatar);
            tvUserName = (TextView) itemView.findViewById(R.id.tvUserName);
            tvLevel = (TextView) itemView.findViewById(R.id.tvLevel);
            ivVip = (ImageView) itemView.findViewById(R.id.ivVip);
            tvInfo = (TextView) itemView.findViewById(R.id.tvInfo);
            tvDesc = (TextView) itemView.findViewById(R.id.tvDesc);
            tvFollow = (TextView) itemView.findViewById(R.id.tvFollow);
            vLine = itemView.findViewById(R.id.vLine);
        }

    }

}
